package org.example.leetCode;

import org.example.entity.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 144. 二叉树的前序遍历
 * 给你二叉树的根节点 root ，返回它节点值的 前序 遍历。
 */
public class Code144 {
    public List<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        dfs(list, root);
        return list;
    }

    private void dfs(ArrayList<Integer> list, TreeNode root) {
        if (root == null) return;
        list.add(root.val);
        dfs(list, root.left);
        dfs(list, root.right);
    }

    public List<Integer> df(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        if (root == null) return list;

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);

        TreeNode node;
        while (!stack.isEmpty()) {
            node = stack.pop();
            list.add(node.val);

            if(node.right!=null){
                stack.push(node.right);
            }
            if(node.left!=null){
                stack.push(node.left);
            }
        }
        return list;
    }
    public List<Integer> d(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        if (root == null) return list;

        TreeNode[] stack=new TreeNode[100];
        int top=0;
        stack[0]=root;

        TreeNode node;
        while (top>=0){
            node=stack[top--];
            list.add(node.val);

            if(node.right!=null){
                stack[++top]=node.right;
            }
            if(node.left!=null){
                stack[++top]=node.left;
            }
        }
        return list;
    }


}
